import 'package:get/get.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/char_x.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/gun_charging_type.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';

class ChargeOrderDetailController extends GetxController {
  List<String> titleList = [
    '${ResKey.gunNumber.tr}：',
    '${ResKey.keyValueID.tr}：',
    '${ResKey.orderFlow.tr}：',
    '${ResKey.userID.tr}：',
    '${ResKey.deviceCode.tr}：',
    '${ResKey.gunType.tr}：',
    '${ResKey.chargeType.tr}：',
    '${ResKey.sourceType.tr}：',
    '${ResKey.chargeStrategy.tr}：',
    '${ResKey.chargingStrategyParam.tr}：',
    '${ResKey.chargeStartTime.tr}：',
    '${ResKey.chargeEndTime.tr}：',
    '${ResKey.startSoc.tr} (%)：',
    '${ResKey.endSoc.tr}(%)：',
    '${ResKey.stopReason.tr}：',
    '${ResKey.stopCode.tr}：',
    '${ResKey.stopChildCode.tr}：',
    '${ResKey.carVin.tr}：',
    '${ResKey.chargeTotalFee.tr}(${ResKey.yuan.tr})：',
    '${ResKey.chargeTotalPower.tr}(kWh)：',
    '${ResKey.chargeTime.tr}(s)：',
    '${ResKey.startMeterReading.tr}(kWh)：',
    '${ResKey.endMeterReading.tr}(kWh)：',
    '${ResKey.totalElectricityCost.tr}(${ResKey.yuan.tr})：',
    '${ResKey.totalServiceFee.tr}(${ResKey.yuan.tr})：',
    '${ResKey.serverType.tr}：',
  ];
  List<String> valueList = [
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
    '--',
  ];
  DeviceServices deviceServices = Get.find();
  Map orderDetail = {};
  List<dynamic> soc = [];

  // List<dynamic> originSoc = [];
  List<dynamic> chargedElectricity = []; //已充电量
  // List<dynamic> originChargedElectricity = []; //已充电量
  List<dynamic> needVoltage = []; //需求电压
  List<dynamic> outVoltage = []; //充电输出电压
  List<dynamic> needCurrent = []; //需求电流
  List<dynamic> outCurrent = []; //充电输出电流
  int divisor = 30; //页面展示的数据条数
  int remainder = 1; //页面取余的数值 通过计算获得
  List list = ChartXDate.getData();

  @override
  void onInit() {
    super.onInit();
    initData();
    if (Get.arguments != null && Get.arguments['orderDetail'] != null) {
      orderDetail = Get.arguments['orderDetail'];
      if (orderDetail['connectorId'] != null) {
        //充电枪号
        valueList[0] = orderDetail['connectorId'].toString();
      }
      if (orderDetail['kid'] != null) {
        valueList[1] = orderDetail['kid'].toString();
      }
      if (orderDetail['startChargeSeq'] != null) {
        valueList[2] = orderDetail['startChargeSeq'].toString();
      }
      if (orderDetail['userId'] != null) {
        valueList[3] = orderDetail['userId'].toString();
      }
      if (orderDetail['connectorId'] != null) {
        valueList[4] = orderDetail['connectorId'].toString();
      }
      if (orderDetail['gumType'] != null) {
        valueList[5] = GunCharging.getGunType(orderDetail);
      }
      if (orderDetail['chargingType'] != null) {
        valueList[6] = GunCharging.getChargingType(orderDetail);
      }
      if (orderDetail['sourceType'] != null) {
        valueList[7] = GunCharging.getSourceType(orderDetail);
      }
      if (orderDetail['chargingStrategy'] != null) {
        valueList[8] = GunCharging.getChargingStrategy(orderDetail);
      }
      if (orderDetail['chargingStrategyParam'] != null) {
        valueList[9] = orderDetail['chargingStrategyParam'].toString();
      }
      if (orderDetail['startTime'] != null) {
        valueList[10] = orderDetail['startTime'].toString();
      }
      if (orderDetail['endTime'] != null) {
        valueList[11] = orderDetail['endTime'].toString();
      }
      if (orderDetail['startSoc'] != null) {
        valueList[12] = orderDetail['startSoc'].toString();
      }
      if (orderDetail['endSoc'] != null) {
        valueList[13] = orderDetail['endSoc'].toString();
      }
      if (orderDetail['stopReason'] != null) {
        valueList[14] = orderDetail['stopReason'].toString();
      }
      if (orderDetail['stopCode'] != null) {
        valueList[15] = orderDetail['stopCode'].toString();
      }
      if (orderDetail['stopSecondCode'] != null) {
        valueList[16] = orderDetail['stopSecondCode'].toString();
      }
      if (orderDetail['carVin'] != null) {
        valueList[17] = orderDetail['carVin'].toString();
      }
      if (orderDetail['totalMoney'] != null) {
        valueList[18] = orderDetail['totalMoney'].toString();
      }
      if (orderDetail['totalPower'] != null) {
        valueList[19] = orderDetail['totalPower'].toString();
      }
      if (orderDetail['chargeDuration'] != null) {
        valueList[20] = orderDetail['chargeDuration'].toString();
      }
      if (orderDetail['startMeter'] != null) {
        valueList[21] = orderDetail['startMeter'].toString();
      }
      if (orderDetail['endMeter'] != null) {
        valueList[22] = orderDetail['endMeter'].toString();
      }
      if (orderDetail['totalElecMoney'] != null) {
        valueList[23] = orderDetail['totalElecMoney'].toString();
      }
      if (orderDetail['totalSeviceMoney'] != null) {
        valueList[24] = orderDetail['totalSeviceMoney'].toString();
      }
      if (orderDetail['serverType'] != null) {
        valueList[25] = GunCharging.getServerType(orderDetail);
      }
    }
  }

  ///初始化数据
  initData() {
    // for (int i = 0; i < list.length; i++) {
    //   var element = list[i];
    //   List tempList = [];
    //   tempList.add(element.substring(11, 16));
    //   tempList.add('--');
    //   originSoc.add(tempList);
    // }
    // originChargedElectricity = List.from(originSoc);
  }

  @override
  void onReady() {
    if (orderDetail['id'] != null) {
      _getSocElectricity(orderDetail['id'].toString());
    }
  }

  @override
  void onClose() {}

  ///获取订单详情
  getOrderDetail() async {
    var result = await deviceServices
        .getGunOrderDetail({'deviceId': '', 'platform': 1}, onError: (error) {
      dismissLoading();
      showError(error.message);
      return false;
    });
  }

  ///获取soc电能曲线
  _getSocElectricity(String orderId) async {
    var param = {
      'keyValue': [
        {
          "key": "mq",
          "deviceId": orderDetail['deviceId'].toString(),
          "name": "电表充电电量",
          'type': 'double'
        },
        {
          "key": "SOC",
          "deviceId": orderDetail['deviceId'].toString(),
          "name": "SOC",
          'type': 'double'
        },
        {
          "key": "gxqu",
          "deviceId": orderDetail['deviceId'].toString(),
          "name": "需求电压",
          'type': 'double'
        },
        {
          "key": "gcu",
          "deviceId": orderDetail['deviceId'].toString(),
          "name": "充电输出电压",
          'type': 'double'
        },
        {
          "key": "gxqi",
          "deviceId": orderDetail['deviceId'].toString(),
          "name": "需求电流",
          'type': 'double'
        },
        {
          "key": "gci",
          "deviceId": orderDetail['deviceId'].toString(),
          "name": "充电输出电流",
          'type': 'double'
        },
      ],
      "pageSize": 1000,
      "startTime": orderDetail['startTime'],
      "endTime": orderDetail['endTime'],
    };
    var result = await deviceServices.getDeviceDataQueryHistorical(param,
        onError: (error) {
      dismissLoading();
      showError(error.message);
      return false;
    });
    // soc = _handleData(originSoc,[]);
    // chargedElectricity = _handleData(originChargedElectricity,[]);
    // update();
    Log.d('getDeviceDataQueryHistorical===' + result.toString());
    if (result != null) {
      List tempList = result;
      List reversedList = List.from(tempList.reversed);
      double referenceData = 0;
      if (reversedList.first != null && reversedList.first['devices'] != null) {
        List list = reversedList.first['devices'];
        for (var element in list) {
          if (element['key'].toString() == 'mq') {
            referenceData = element['value'];
          }
        }
      }

      for (var element in reversedList) {
        if (element['time'] != null) {
          var time = element['time'].toString().substring(11, 19);
          List deviceList = element['devices'];
          for (var device in deviceList) {
            if (device['key'].toString() == 'SOC' && device['value'] != null) {
              List list = [time, device['value']];
              soc.add(list);
            }
            if (device['key'].toString() == 'mq' && device['value'] != null) {
              double value = device['value'] - referenceData;
              List list = [time, value.toStringAsFixed(2)];
              chargedElectricity.add(list);
            }
            if (device['key'].toString() == 'gxqu' && device['value'] != null) {
              List list = [time, device['value']];
              needVoltage.add(list);
            }
            if (device['key'].toString() == 'gcu' && device['value'] != null) {
              List list = [time, device['value']];
              outVoltage.add(list);
            }
            if (device['key'].toString() == 'gxqi' && device['value'] != null) {
              List list = [time, device['value']];
              needCurrent.add(list);
            }
            if (device['key'].toString() == 'gci' && device['value'] != null) {
              List list = [time, device['value']];
              outCurrent.add(list);
            }
          }
        }
      }
      update();
    }
  }

  List<dynamic> _handleData(List originList, List? dataList) {
    List<dynamic> returnList = [];
    Log.d('originList==' + originList.toString());
    if (dataList != null && dataList.isNotEmpty) {
      Map map = {};
      for (var element in dataList) {
        map[element['eventTs'].substring(11, 16)] = element['val'];
      }
      for (var element in originList) {
        List<dynamic> elementList = List.from(element);
        if (map[elementList[0]] != null) {
          elementList[1] = map[elementList[0]].toString();
        }
        returnList.add(elementList);
      }
    } else {
      returnList = List.from(originList);
    }

    return returnList;
  }

  List<dynamic> showData(
    List originList,
  ) {
    List<dynamic> returnList = [];
    for (int i = 0; i < originList.length; i++) {
      var element = originList[i];
      if (i % remainder == 0) {
        returnList.add(element);
      }
    }
    Log.d('returnList==' + returnList.toString());
    return returnList;
  }
}
